package com.example.score.controller;

import com.example.score.config.BstaConfig;
import com.example.score.config.ServerConfig;
import com.example.score.dto.AjaxResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

@RestController
@RequestMapping("/common")
public class CommonController {

    @Autowired
    private ServerConfig serverConfig;

    @PostMapping("/upload")
    public AjaxResult uploadFile(MultipartFile file) {
        try {
            // 生成日期目录
            String datePath = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy/MM/dd"));
            // 上传文件路径
            String uploadPath = BstaConfig.getUploadPath();
            String filePath = uploadPath + "/" + datePath;
            
            // 创建目录
            File directory = new File(filePath);
            if (!directory.exists()) {
                if (!directory.mkdirs()) {
                    return AjaxResult.error("创建目录失败");
                }
            }

            // 获取文件名
            String fileName = file.getOriginalFilename();
            // 文件完整路径
            String fullPath = filePath + "/" + fileName;
            // 相对路径（用于URL）
            String relativePath = "/upload/" + datePath + "/" + fileName;

            // 构建URL
            String url;
            if (serverConfig.getAddress().contains("localhost")) {
                url = serverConfig.getUrl() + relativePath;
            } else if (serverConfig.getAddress().contains("test") || serverConfig.getAddress().contains("prod")) {
                url = serverConfig.getUrl().replace("http:", "https:") + relativePath;
            } else {
                url = serverConfig.getUrl() + relativePath;
            }
            
            // 保存文件
            File dest = new File(fullPath);
            file.transferTo(dest);

            AjaxResult ajax = AjaxResult.success();
            ajax.put("url", url);
            ajax.put("fileName", relativePath);
            ajax.put("newFileName", fileName);
            ajax.put("originalFilename", file.getOriginalFilename());
            ajax.put("fileSize", file.getSize());
            return ajax;
            
        } catch (IOException e) {
            return AjaxResult.error(e.getMessage());
        }
    }
}